//
//  ImageCell.swift
//  CellAutolayoutHeight
//
//  Created by zk_01 on 2022/3/29.
//

import UIKit
import Kingfisher

class ImageCell: BaseCell {

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
            
        self.stackView.snp.makeConstraints { make in
            make.top.equalTo(self.portraitImgView.snp.bottom).offset(10.0)
            make.left.right.equalTo(self.nameLab)
            make.height.equalTo(80.0)
            make.bottom.lessThanOrEqualTo(-10)
        }
        
        self.hotTopicsStackView.snp.makeConstraints { make in
            make.top.equalTo(self.stackView.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalTo(self.bottomBarStackView.snp.top).offset(-10).priority(500)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.stackView.subviews.forEach { v in
            v.addCorners(.allCorners, cornerRadii: CGSize(width: 5, height: 5))
        }
    }
    
    override func setModel(_ model: DataModel) {
        super.setModel(model)
        
        self.stackView.snp.updateConstraints { make in
            make.height.equalTo(model.imgsUrl.count == 1 ? 160.0 : 80.0)
        }
        
        self.stackView.subviews.forEach { v in
            v.removeFromSuperview()
        }
        
        model.imgsUrl.forEach({ imgUrl in
            let imgV = UIImageView()
            imgV.contentMode = .scaleAspectFill
            
            //下载图片，动画显示
            imgV.kf.setImage(with: ImageResource.init(downloadURL: URL(string:imgUrl)!),
                                           placeholder: UIImage(named: "portraitImage"),
                                           options:  [.transition(ImageTransition.fade(1))],
                                           progressBlock: { (receivedSize, totalSize) in
            }) { res in
                
            }

            self.stackView.addArrangedSubview(imgV)
        })
        
        self.hotTopicsStackView.subviews.forEach { v in
            v.removeFromSuperview()
        }
        model.hotTopics.forEach { hot in
            let lab = UILabel()
            lab.text = "#" + hot.title
            lab.textColor = .systemBlue
            lab.textAlignment = .left
            lab.font = .systemFont(ofSize: 16.0)
            self.hotTopicsStackView.addArrangedSubview(lab)
        }
    }
    
    lazy var stackView: UIStackView = {
        let stackView = UIStackView(arrangedSubviews: [UIView]())
        stackView.axis = .horizontal
        stackView.spacing = 10.0
        stackView.distribution = .fillEqually
        self.contentView.addSubview(stackView)
        return stackView
    }()
}
